﻿using System;
using System.Text;
using PcapDotNet.Core;
using PcapDotNet.Core.Extensions;

namespace MolyMade.Mute
{
    public static class Mac
    {
        private static int _randomSeed;
        public static string Null = "00-00-00-00-00-00";
        public static string Broadcast= "FF-FF-FF-FF-FF-FF";
        public static string Random => RandomMacAddress();
        public static string Device(LivePacketDevice device) => device.GetMacAddress().ToString();
        public static byte[] NullAsBytes => MacStringToBytes(Null);
        public static byte[] BroadcastAsBytes => MacStringToBytes(Broadcast);
        public static byte[] RandomAsBytes => MacStringToBytes(RandomMacAddress());
        public static byte[] ToBytes(string macAddress) => MacStringToBytes(macAddress);
       
        /// <summary>
        /// Generate a random MAC address.
        /// </summary>
        private static string RandomMacAddress()
        {
            Random random = new Random(_randomSeed);
            _randomSeed = random.Next();
            StringBuilder sb = new StringBuilder();
            sb.Append((random.Next(0,256) & 252 | 2).ToString("X2"));
            for (int i = 1; i < 6; i++)
            {
                sb.Append(":");
                sb.Append(random.Next(0,256).ToString("X2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// Convert MAC address from string to byte[6].
        /// </summary>
        private static byte[] MacStringToBytes(string s)
        {
            var values = s.Split(':');
            byte[] retBytes = new byte[6];
            for (int i = 0; i < 6; i++)
            {
                retBytes[i] = Convert.ToByte(values[i],16);
            }
            return retBytes;
        }
        
    }
}
